package com.wwwarehouse.contract.contract;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.custom_widget.time_pick.ChoosePickerDialog;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tools.rsa.StringUtils;
import com.wwwarehouse.contract.bean.ObligationItemEvent;
import com.wwwarehouse.contract.bean.ReleaseObligationLoadBean;
import com.wwwarehouse.contract.core.ContractConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

import static contract.wwwarehouse.com.contract.R.string.discount;
import static contract.wwwarehouse.com.contract.R.string.rongren;
import static java.lang.Double.parseDouble;


/**
 * 义务项Fragment
 * Created by ShineF on 2017/10/17 0017.
 */

public class ReleaseObligationItemFragment extends BaseFragment implements View.OnClickListener {


    private RelativeLayout mRlRewardAndPunishment;
    private RelativeLayout mRlDiscountNum;
    private TextView mTvRewardAndPunishment;
    private List<String> mPickerList;
    private static final int SAVE_OBLIGATION_ITEM = 1;
    private static final int DECIMAL_DIGITS = 1;
    private static final int RELEASE_OBLIGATION_URL = 5;
    private Button mBtnSave = null;
    private int mRewandType = -1;
    private ClearEditText mDiscountNum;
    private ClearEditText mMaxNum;
    private ClearEditText mMinNum;
    private TextInputLayout mMaxLayout;
    private TextInputLayout mMinLayout;
    private TextInputLayout mDiscountLayout;
    private String pbUkid;
    private TextView mTvWarnning;
    private String mType;
    private String contractId;
    private Long mObligationOrderUkid;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_release_obligation_item, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRlRewardAndPunishment = $(R.id.rl_reward_and_punishment);
        mTvRewardAndPunishment = $(R.id.tv_select_reward_and_punishment);
        mRlDiscountNum = $(R.id.rl_discount_num);
        mBtnSave = $(R.id.btn_save);
        mDiscountNum = $(R.id.cet_discount_number);
        mMinNum = $(R.id.cet_min_num);
        mMaxNum = $(R.id.cet_max_num);
        mMaxLayout = $(R.id.til_max);
        mMinLayout = $(R.id.til_min);
        mDiscountLayout = $(R.id.til_discount);
        mTvWarnning = $(R.id.tv_warnning_info);
        mBtnSave.setEnabled(false);
        showProgressDialog("正在加载...");
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ReleaseObligationItemFragment) {
            mActivity.setTitle(getString(R.string.obligation_item_title));
        }
    }

    @Override
    public void requestDatas() {
        Bundle bundle = getArguments();
        if (null == bundle) {
            return;
        }
        pbUkid = bundle.getString(ContractConstant.KEY_DELIVERY_ITEM_PBUKID);
        Boolean isCreate = bundle.getBoolean(ContractConstant.KEY_BOOLEAN_DELIVERY_ITEM_IS_CREATE);
        mObligationOrderUkid = bundle.getLong(ContractConstant.KEY_BOOLEAN_OBLIGATION_ITEM_ORDER_ID);
        mType = bundle.getString("type");
        contractId = bundle.getString(ContractConstant.KEY_MODIFY_PAYMENT_ITEM_CONTRACT_UKID);
        mBtnSave.setOnClickListener(this);
        mRlRewardAndPunishment.setOnClickListener(this);
        mPickerList = new ArrayList<>();
        mPickerList.add(getString(rongren));
        mPickerList.add(getString(discount));
        filterEditText();
        if (mType == null) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        if (isCreate) {
            dismissProgressDialog();
            return;
        }
        if (mType.equals(ContractConstant.RELEASE_SUPPLY_FUNCTION_RELEASE)
                || mType.equals(ContractConstant.RELEASE_SUPPLY_TASK_RELEASE)) {
            map.put("contractUkid", pbUkid);
            map.put("type", 1);
        }
        if (mType.equals(ContractConstant.RELEASE_SUPPLY_FUNCTION_EDIT)) {
            map.put("contractUkid", contractId);
            map.put("type", 2);
        }
        loadData(ContractConstant.RELEASE_OBLIGATION_URL, map, RELEASE_OBLIGATION_URL);
    }

    public void filterEditText() {
        mMaxNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + DECIMAL_DIGITS + 1);
                        mMaxNum.setText(s);
                        mMaxNum.setSelection(s.length());
                    }
                }
                if (s.toString().trim().equals(".")) {
                    s = "0" + s;
                    mMaxNum.setText(s);
                    mMaxNum.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        mMaxNum.setText(s.subSequence(0, 1));
                        mMaxNum.setSelection(1);
                    }
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().equals(".")) {
                    return;
                }
                if (TextUtils.isEmpty(editable.toString())) {
                    mMaxLayout.setStateNormal();
                    return;
                }
                if (Double.valueOf(editable.toString()) <= 0) {
                    mMaxLayout.setStateWrong("时间必须大于0");
                    return;
                } else {
                    mMaxLayout.setStateNormal();
                }
                Double max = Double.valueOf(editable.toString());
                String minS = mMinNum.getText().toString().trim();
                if (TextUtils.isEmpty(minS)) {
                    mMinLayout.setStateNormal();
                    return;
                }
                Double min = Double.valueOf(minS);
                if (min > max || Objects.equals(min, max)) {
                    mMaxLayout.setStateWrong("必须大于最小超时时间");
                } else if (min <= 0) {
                    mMaxLayout.setStateNormal();
                } else {
                    mMinLayout.setStateNormal();
                    mMaxLayout.setStateNormal();
                }
                filterButton();
            }
        });
        mMinNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + DECIMAL_DIGITS + 1);
                        mMinNum.setText(s);
                        mMinNum.setSelection(s.length());
                    }
                }
                if (s.toString().trim().equals(".")) {
                    s = "0" + s;
                    mMinNum.setText(s);
                    mMinNum.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        mMinNum.setText(s.subSequence(0, 1));
                        mMinNum.setSelection(1);
                    }
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().equals(".")) {
                    return;
                }
                if (TextUtils.isEmpty(editable.toString())) {
                    mMaxLayout.setStateNormal();
                    mMinLayout.setStateNormal();
                    return;
                }
                if (Double.valueOf(editable.toString()) <= 0) {
                    mMinLayout.setStateWrong("时间必须大于0");
                    return;
                } else {
                    mMinLayout.setStateNormal();
                }
                Double min = Double.valueOf(editable.toString());
                String maxS = mMaxNum.getText().toString().trim();
                if (TextUtils.isEmpty(maxS)) {
                    return;
                }
                Double max = Double.valueOf(maxS);
                if (min > max || Objects.equals(min, max)) {
                    mMinLayout.setStateWrong(" 必须小于最大超时时间");
                } else if (0 == max) {
                    mMinLayout.setStateNormal();
                } else {
                    mMinLayout.setStateNormal();
                    mMaxLayout.setStateNormal();
                }
                filterButton();
            }
        });
        mDiscountNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + DECIMAL_DIGITS + 1);
                        mDiscountNum.setText(s);
                        mDiscountNum.setSelection(s.length());
                    }
                }
                if (s.toString().trim().equals(".")) {
                    s = "0" + s;
                    mDiscountNum.setText(s);
                    mDiscountNum.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        mDiscountNum.setText(s.subSequence(0, 1));
                        mDiscountNum.setSelection(1);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().equals(".")) {
                    return;
                }
                if (!TextUtils.isEmpty(editable.toString())) {
                    if (Double.valueOf(editable.toString()) == 0) {
                        mDiscountLayout.setStateWrong("打折数不能小于0");
                        return;
                    }
                    String discountNumS = mDiscountNum.getText().toString().trim();
                    if (!TextUtils.isEmpty(discountNumS)) {
                        Double discountNum = Double.valueOf(discountNumS);
                        if (discountNum > 10) {
                            mDiscountLayout.setStateWrong(" 打折数不能超过10");
                        } else if (discountNum == 10) {
                            mDiscountLayout.setStateWrong(" 打折数不能等于10");
                        } else {
                            mDiscountLayout.setStateNormal();
                        }
                    }
                } else {
                    mDiscountLayout.setStateNormal();
                }
                filterButton();
            }
        });
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.rl_reward_and_punishment) {
            new ChoosePickerDialog.Builder(mActivity)
                    .setData(mPickerList)
                    .setTitle("选择奖惩措施")
                    .setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
                        @Override
                        public void onSelected(String s, int i) {
                            mTvRewardAndPunishment.setText(s);
                            if (s.equals(getString(discount))) {
                                mRlDiscountNum.setVisibility(View.VISIBLE);
                                mRewandType = 1;
                            } else {
                                mRlDiscountNum.setVisibility(View.GONE);
                                mRewandType = 0;
                            }
                            filterButton();
                        }

                        @Override
                        public void onCancel() {

                        }
                    })
                    .create()
                    .show();
        } else if (view.getId() == R.id.btn_save) {
            String minNum = mMinNum.getText().toString().trim();
            String maxNum = mMaxNum.getText().toString().trim();
            Map<String, Object> map = new HashMap<>();
            map.put("defaultType", "0");
            map.put("defaultValueMax", maxNum);
            map.put("defaultValueMin", minNum);
            if (mObligationOrderUkid != 0) {
                map.put("obligationOrderUkid", mObligationOrderUkid);
            }
            if (mRewandType == 1) {
                String rewandValue = mDiscountNum.getText().toString().trim();
                Double disCountD = parseDouble(rewandValue);
                int disCountNum = (int) (disCountD * 10);
                map.put("rewandValue", disCountNum);
            }
            map.put("rewandType", mRewandType);
            if (mType.equals(ContractConstant.RELEASE_SUPPLY_FUNCTION_RELEASE) || mType.equals(ContractConstant.RELEASE_SUPPLY_TASK_RELEASE)) {
                map.put("contractUkid", pbUkid);
                map.put("type", 1);
            } else if (mType.equals(ContractConstant.RELEASE_SUPPLY_FUNCTION_EDIT)) {
                map.put("contractUkid", contractId);
                map.put("type", 2);
            }
            loadData(ContractConstant.SAVE_RELEASE_OBLIGATION_URL, map, SAVE_OBLIGATION_ITEM);
        }
    }

    public void loadData(String url, Map map, int what) {
        NoHttpUtils.httpPost(url, map, new NoHttpUtils.OnResponseListener() {
            @Override
            public void onSucceed(CommonClass commonClass, int what) {
                if (SAVE_OBLIGATION_ITEM == what) {
                    if (commonClass.getCode().equals("0")) {
                        String data = commonClass.getData().toString();
                        if (!TextUtils.isEmpty(data)) {
                            String rewardType = mTvRewardAndPunishment.getText().toString().trim();
                            String disCount = mDiscountNum.getText().toString().trim();
                            String minNum = mMinNum.getText().toString().trim();
                            String maxNum = mMaxNum.getText().toString().trim();
                            ObligationItemEvent event = new ObligationItemEvent();
                            event.setObligationTempUkid(data);
                            event.setData(StringUtils.getResourceStr(mActivity, R.string.obligation_time_card, minNum, maxNum));
                            if (!TextUtils.isEmpty(rewardType) && rewardType.equals(getString(discount))) {
                                event.setDiscount(true);
                                event.setDiscount(disCount);
                            } else {
                                event.setDiscount(false);
                            }
                            EventBus.getDefault().post(event);
                            popFragment();
                        }
                    } else {
                        ToastUtils.showToast(commonClass.getMsg());
                    }
                } else if (RELEASE_OBLIGATION_URL == what) {
                    if ("0".equals(commonClass.getCode())) {
                        List<ReleaseObligationLoadBean> loadBean = JSON.parseArray(commonClass.getData().toString(), ReleaseObligationLoadBean.class);
                        if (null == loadBean) {
                            return;
                        }
                        if (loadBean.size() == 0) {
                            return;
                        }
                        setData(loadBean);
                    }
                }
            }

            @Override
            public void onFailed(String s, int i) {

            }

            @Override
            public void onFinish(int i) {

            }
        }, what);
    }

    private void setData(List<ReleaseObligationLoadBean> loadBean) {
        ReleaseObligationLoadBean releaseObligationLoadBean = loadBean.get(0);
        mRewandType = releaseObligationLoadBean.getRewandType();
        if (releaseObligationLoadBean.getDefaultType() == 0) {
            mTvWarnning.setText("到货超时");
        } else if (releaseObligationLoadBean.getDefaultType() == 1) {
            mTvWarnning.setText("到货缺量");
        }
        mMinNum.setText(releaseObligationLoadBean.getDefaultValueMin());
        mMinLayout.setStateNormal();
        mMaxNum.setText(releaseObligationLoadBean.getDefaultValueMax());
        mMaxLayout.setStateNormal();
        if (releaseObligationLoadBean.getRewandType() == 1) {
            mTvRewardAndPunishment.setText(getString(discount));
            float rewandValue = (float) releaseObligationLoadBean.getRewandValue();
            mDiscountNum.setText(String.valueOf(rewandValue / 10f));
            mDiscountLayout.setStateNormal();
            mRlDiscountNum.setVisibility(View.VISIBLE);
        } else if (releaseObligationLoadBean.getRewandType() == 0) {
            mTvRewardAndPunishment.setText(getString(rongren));
            mRlDiscountNum.setVisibility(View.GONE);
        }
        dismissProgressDialog();
        filterButton();
    }

    public void filterButton() {
        String minNum = mMinNum.getText().toString().trim();
        String maxNum = mMaxNum.getText().toString().trim();
        String rewardType = mTvRewardAndPunishment.getText().toString().trim();
        String disCount = mDiscountNum.getText().toString().trim();
        if (rewardType.equals(getString(R.string.select_reward_and_punishment))
                || (rewardType.equals(getString(discount)) && TextUtils.isEmpty(disCount))) {
            mBtnSave.setEnabled(false);
            mBtnSave.setSelected(false);
            return;
        }
        if (TextUtils.isEmpty(minNum)
                || TextUtils.isEmpty(maxNum)
                || parseDouble(minNum) > parseDouble(maxNum)
                || parseDouble(minNum) == parseDouble(maxNum)
                || parseDouble(minNum) <= 0
                || parseDouble(maxNum) <= 0) {
            mBtnSave.setEnabled(false);
            mBtnSave.setSelected(false);
            return;
        }
        if (rewardType.equals(getString(R.string.rongren))) {
            mBtnSave.setEnabled(true);
            mBtnSave.setSelected(true);
            return;
        }
        double disCountNum = Double.parseDouble(disCount);
        if (rewardType.equals(getString(discount)) && (disCountNum >= 10 || disCountNum <= 0)) {
            mBtnSave.setEnabled(false);
            mBtnSave.setSelected(false);
            return;
        }
        mBtnSave.setEnabled(true);
        mBtnSave.setSelected(true);
    }
}